import {
  init,
  classModule,
  eventListenersModule,
  h,
} from "snabbdom";

const patch = init([
  classModule,
  eventListenersModule, // attaches event listeners
]);
let sortBy = "rank";
let list = [
  {
    rank: 1,
    title: '爱在西元前',
    description: '我对你的爱在那西元前。。。'
  },
  {
    rank: 2,
    title: '菊花台',
    description: '菊花残，满地伤，你的笑容已泛黄。。。'
  },
  {
    rank: 3,
    title: '听妈妈的话',
    description: '听妈妈的话，别让她受伤，想快快长大，才能保护她。。。'
  },
  {
    rank: 4,
    title: '千里之外',
    description: '屋檐如悬崖，风铃如沧海，我等燕归来。。。'
  },
  {
    rank: 5,
    title: '七里香',
    description: '秋刀鱼的滋味，猫跟你都想了解，初恋的香味就这样被我们寻回。。。'
  },
  {
    rank: 6,
    title: '东风破',
    description: '一壶漂泊，浪迹天涯难入喉，你走之后，酒暖回忆思念瘦。。。'
  },
]

let oldVnode = document.querySelector('#container');
render(list)

function render(list) {
  const vnode = h("div#container.two.classes", [
    h('h1', 'Top 10 Songs'),
    h('p', [
      'Sort by:',
      h('span.ml-8', { 
        on: { click: () => { sort('rank') } },
        class: { current: sortBy === 'rank' }
      }, 'Rank'),
      h('span.ml-8', { 
        on: { click: () => { sort('title') } },
        class: { current: sortBy === 'title' },
      }, 'Title'),
      h('span.ml-8', { 
        on: { click: () => { sort('description') } },
        class: { current: sortBy === 'description' },
      }, 'Description'),
      h('span.add', { on: { click: add } }, 'Add'),
    ]),
    h('ul', list.map((item, i) => {
      return h('li', [
        h('span', item.rank),
        h('span', item.title),
        h('span', item.description),
        h('span', { on: { click: () => { remove(i) } } }, 'x'),
      ])
    }))
  ]);
  oldVnode = patch(oldVnode, vnode);
}

function sort(type) {
  sortBy = type;
  list = list.sort((a, b) => {
    return a[type] > b[type] ? 1 : -1
  })
  render(list)
}

function add() {
  const rank = getMaxRank(list) + 1;
  const tempItem = {
    rank,
    title: '新增标题 '+ rank, 
    description: '新增描述 '+ rank, 
  }
  list.push(tempItem);
  render(list);
}
function getMaxRank(list) {
  return Math.max(...list.map(item => item.rank));
}

function remove(i) {
  list.splice(i, 1);
  render(list);
}